const db = uniCloud.database();
const dbCmd = db.command;
module.exports = {
	_before: function () { // 通用预处理器

	},
	
	async addAddress(obj){
		let {user_id,name,mobile,gander,address,house_number,is_default}=obj;
		if(is_default==true){
		        await db.collection("address").where({
					is_default:true,
					user_id
				}).update({
					is_default:false,
				})
			}
		let res=await db.collection("address").add({
			user_id,name,mobile,gander,address,house_number,is_default
		})
	},
	
	async getAddress(user_id){
		let res=await db.collection("address").where({
			user_id
		}).get();
		return res;	
	},
	
	async getAddressBYID(address_id){
		let res=await db.collection("address").where({
			_id:address_id
		}).get();
		return res;	
	},
	
	async updateAddressBYID(selectAddress){
		let {user_id,name,mobile,gander,address,house_number,is_default,_id}=selectAddress;
		if(is_default==true){
		        await db.collection("address").where({
					is_default:true,
					user_id
				}).update({
					is_default:false,
				})
			}
		let res=await db.collection("address").where({
			user_id,
			_id
		}).update({
			name,mobile,gander,address,house_number,is_default
		});
		return res;	
	},
	
	async getDefaultAddress(user_id){
		let res=db.collection("address").where({
			user_id,
			is_default:true
		}).get();
		return res;
	}
}
